package com.party.mobile.biz.crowdfund;

import com.alibaba.fastjson.JSONObject;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.crowdfund.CrowdfundEvent;
import com.party.core.model.crowdfund.Project;
import com.party.core.model.crowdfund.Support;
import com.party.core.model.crowdfund.TargetProject;
import com.party.core.model.distributor.DistributorCount;
import com.party.core.model.distributor.DistributorDetailType;
import com.party.core.model.distributor.DistributorRelation;
import com.party.core.model.member.Member;
import com.party.core.model.order.OrderForm;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.crowdfund.ISupportService;
import com.party.core.service.crowdfund.ITargetProjectService;
import com.party.core.service.distributor.IDistributorCountService;
import com.party.core.service.distributor.IDistributorRelationService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.order.IOrderFormService;
import com.party.mobile.biz.analyze.MemberCopartnerDetailBizService;
import com.party.mobile.biz.distributor.DistributorBizService;
import com.party.mobile.biz.file.FileBizService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.crowdfund.input.SupportStatisticsInput;
import com.party.mobile.web.dto.crowdfund.output.SupportDiplomaOutput;
import com.party.mobile.web.dto.distributor.input.ApplyDistributorInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.function.Function;

/**
 * 支持业务接口
 * Created by wei.li
 *
 * @date 2017/3/28 0028
 * @time 11:03
 */

@Service
public class SupportBizService {

    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private DistributorBizService distributorBizService;

    @Autowired
    private IDistributorRelationService distributorRelationService;

    @Autowired
    private IDistributorCountService distributorCountService;

    @Autowired
    private ISupportService supportService;

    @Autowired
    private IOrderFormService orderFormService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private ITargetProjectService targetProjectService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private CosBizService cosBizService;

    @Autowired
    private FileBizService fileBizService;

    @Autowired
    private MemberCopartnerDetailBizService memberCopartnerDetailBizService;

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    @Value("#{party['mic.url']}")
    private String micUrl;

    /**
     * @param input       参数
     * @param disRelation 分销关系
     * @param isSuccess   成功状态
     * @param fn          回调函数
     * @return
     * @Author yifeng
     * @Description 维护支持关系，分销数据
     * @Date 17:48 2019/4/18
     **/
    public void statistics(SupportStatisticsInput input, DistributorRelation disRelation, boolean isSuccess, Function fn) {
        logger.error("支持统计data：{}", JSONObject.toJSONString(input));
        if (null != disRelation) {
            ApplyDistributorInput applyDistributorInput = new ApplyDistributorInput();
            applyDistributorInput.setDistributorTargetId(disRelation.getTargetId());
            applyDistributorInput.setDistributorType(disRelation.getType());
            applyDistributorInput.setDistributorId(disRelation.getDistributorId());
            applyDistributorInput.setDistributorParentId(disRelation.getParentId());
            applyDistributorInput.setTargetId(input.getSupportId());
            applyDistributorInput.setType(DistributorDetailType.DISTRIBUTOR_TYPE_SUPPORT.getCode());
            boolean result = distributorBizService.setDistributorData(applyDistributorInput, disRelation);
            if (result) {
                distributorBizService.distributorCount(disRelation.getId(), applyDistributorInput.getType(), input.getPayment(), isSuccess);
                if (null != fn) {
                    fn.apply(null);
                }
            }
        }
    }


    /**
     * 统计支持数据
     * @param input 输入视图
     */
    public void statistics(SupportStatisticsInput input) {
        logger.info("支持统计data：{}", JSONObject.toJSONString(input));

        DistributorRelation distributorRelation = distributorBizService.getDistributorRelation(input.getProjectId());

        if (null != distributorRelation) {
            ApplyDistributorInput applyDistributorInput = new ApplyDistributorInput();
            applyDistributorInput.setDistributorTargetId(distributorRelation.getTargetId());
            applyDistributorInput.setDistributorType(distributorRelation.getType());
            applyDistributorInput.setDistributorId(distributorRelation.getDistributorId());
            applyDistributorInput.setDistributorParentId(distributorRelation.getParentId());
            applyDistributorInput.setTargetId(input.getSupportId());
            applyDistributorInput.setType(DistributorDetailType.DISTRIBUTOR_TYPE_SUPPORT.getCode());
            boolean result = distributorBizService.setDistributorData(applyDistributorInput);
            if (result) {

                DistributorCount distributorCount = distributorCountService.findByRelationId(distributorRelation.getId());
                if (null == distributorCount) {
                    throw new BusinessException("分销统计不存在");
                }

                Float amount = BigDecimalUtils.add(distributorCount.getFavorerAmount(), input.getPayment());
                amount = BigDecimalUtils.round(amount, 2);
                distributorCount.setFavorerAmount(amount);

                distributorCountService.update(distributorCount);

                try {
                    memberCopartnerDetailBizService.updateOrderAnalyze(input.getProjectId(), input.getPayment());
                } catch (Exception e) {
                    logger.error("实时更新合伙人订单统计数异常", e);
                }
            }
        }
    }

    /**
     * 获取支持证书数据
     * @param id: 支持id
     * @return
     */
    public AjaxResult getDiplomaData(String id) {
        try {
            if (StringUtils.isEmpty(id)) {
                return AjaxResult.error(99999, "支持id不能为空");
            }
            Support support = supportService.get(id);
            if (null == support) {
                return AjaxResult.error(99998, "支持id找不到对应的支持信息");
            }
            // 订单
            OrderForm orderForm = orderFormService.get(support.getOrderId());
            // 支持者
            Member supportMember = memberService.get(support.getFavorerId());
            // 众筹
            Project project = projectService.get(support.getProjectId());
            // 众筹报名者
            Member projectMember = memberService.get(project.getAuthorId());
            // 众筹目标
            TargetProject targetProject = targetProjectService.findByProjectId(project.getId());
            // 众筹项目
            Activity activity = activityService.get(targetProject.getTargetId());

            SupportDiplomaOutput output = new SupportDiplomaOutput();
            output.setMoney(orderForm.getPayment().toString());
            output.setProject(project.getTitle());
            output.setSupporterName(supportMember.getRealname());
            output.setSupporterLogo(supportMember.getLogo());
            output.setProjectorName(projectMember.getRealname());
            output.setProjectorLogo(projectMember.getLogo());
            output.setProjectId(activity.getId());
            output.setProjectMember(activity.getMember());

            CrowdfundEvent crowdfundEvent = crowdfundEventService.findByProjectId(support.getProjectId());
            if (YesNoStatus.NO.getCode().equals(crowdfundEvent.getIsMultiple())) {
                // 众筹项目页面链接
                String detailContent = "project/target_client_detail.html?id=" + activity.getId();
                String url = micUrl + detailContent;
                output.setProjectQrCode(url);
            } else if (YesNoStatus.NO.getCode().equals(crowdfundEvent.getIsMultiple())) {
                // 众筹项目页面链接
                String detailContent = "project/target_multi_detail.html?id=" + activity.getId();
                String url = micUrl + detailContent;
                output.setProjectQrCode(url);
            }
            // 众筹项目
            String detailFileName = "detail_" + activity.getId();
            String filePath = fileBizService.getUploadCIPath(activity.getMember(), "zcActivity");
            String detailQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + detailFileName);
            output.setProjectQrCodeImg(detailQrCodeUrl);
            return AjaxResult.success(output);
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }

    /**
     * 画支持证书
     * @param id: 支持id
     * @return
     */
    public File paintDiploma(String id) {
        AjaxResult ajaxResult = getDiplomaData(id);
        if (!ajaxResult.isSuccess()) {
            throw new BusinessException(ajaxResult.getDescription());
        }
        SupportDiplomaOutput supportDiplomaOutput = (SupportDiplomaOutput) ajaxResult.getData();


        String filePath = fileBizService.getUploadCIPath(supportDiplomaOutput.getProjectMember(), "zcActivity");
        String detailFileName = "detail_" + supportDiplomaOutput.getProjectId();
        String detailQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + detailFileName);
        return null;
    }
}
